package com.missyoubug.easyjtest.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;
import java.io.File;

@Configuration
@PropertySource("classpath:application-project.properties")
public class DataSourceConfig {

    @Autowired
    private Environment env;
    @Bean("projectDataSourceInitializer")
    public DataSourceInitializer projectDataSourceInitializer(DataSource dataSource) {
        ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
        resourceDatabasePopulator.addScript(new ClassPathResource("initialization.sql"));

        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);

        return dataSourceInitializer;
    }
    @Bean(name = "projectDataSource")
    public DataSource projectDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        // 设置驱动类名、用户名和密码
        dataSource.setDriverClassName(env.getProperty("project.datasource.driverClassName"));
        dataSource.setUsername(env.getProperty("project.datasource.username"));
        dataSource.setPassword(env.getProperty("project.datasource.password"));

        // 动态设置数据源URL
        String url = getUrlBasedOnDiskAvailability();
        dataSource.setUrl(url);

        return dataSource;
    }

    private String getUrlBasedOnDiskAvailability() {
        // 检查D盘是否存在并且是可用的
        File dDrive = new File("D:");
        if (dDrive.exists() && dDrive.canWrite()) {
            // 如果D盘存在且可写，则返回D盘下的路径
            return "jdbc:h2:file:D:/data/mydb;AUTO_SERVER=TRUE";
        } else {
            // 否则返回默认路径
            return env.getProperty("bproject.datasource.url");
        }
    }
}